package com.zhiwang.planet.mvvm.viewmodel.withdraw

import android.annotation.SuppressLint
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.switchMap
import androidx.paging.DataSource
import androidx.paging.PageKeyedDataSource
import androidx.paging.PagedList
import androidx.paging.toLiveData
import com.google.gson.reflect.TypeToken
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.main.WithDrawRecord
import com.zhiwang.planet.util.ReflectUtil
import com.zhiwang.planet.util.responseFunc
import java.lang.IllegalStateException
import java.lang.reflect.ParameterizedType


class ItemPagedKeyDataSource constructor(val restApi: RestApi) : PageKeyedDataSource<Int, WithDrawRecord>() {


    val refreshing = MutableLiveData<PagedList.LoadState>()

    val loading = MutableLiveData<PagedList.LoadState>()

    val err = MutableLiveData<Throwable>()

    val initLoadDone = MutableLiveData<Boolean>()


    @SuppressLint("CheckResult")
    override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, WithDrawRecord>) {
        refreshing.postValue(PagedList.LoadState.LOADING)

        restApi
                .getWithDrawRecord(1)
                .responseFunc()
                .subscribe({

                    callback.onResult(it.data, 0, 2)
                    initLoadDone.postValue(true)
                    refreshing.postValue(PagedList.LoadState.DONE)
                }, {
                    err.postValue(it)
                    initLoadDone.postValue(true)
                }, {

                })

    }

    @SuppressLint("CheckResult")
    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, WithDrawRecord>) {
        val key = params.key
        loading.postValue(PagedList.LoadState.LOADING)

        restApi.getWithDrawRecord(key)
                .responseFunc()
                .subscribe({

                    callback.onResult(it.data, key + 1)
                    loading.postValue(PagedList.LoadState.DONE)
                }, {

                    err.postValue(it)
                }, {

                })

    }


    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, WithDrawRecord>) {
        //no prepending logic
    }


}





